/**
 * Captain
 * © 2018 Captain copyright，All rights reserved.
 * http://www.sccaptain.com.cn
 * 
 * JAVA : 8
 * 文  件  名: ShoppingCardServiceImpl.java
 * 创  建  人: QinYoubin (qin.youbin@sccaptain.com.cn)
 * 创建时间: 2018年5月2日 下午1:57:13
 * 版         本: 1.0.0
 * 备         注:
 * 修订历史:
 */
package com.material.c2c.shoping.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.cpt.framework.core.OperationResult;
import com.material.c2c.commodity.dao.CommInfoDao;
import com.material.c2c.commodity.entity.SPXX;
import com.material.c2c.config.ShoppingCartStatus;
import com.material.c2c.core.UUIDGenerator;
import com.material.c2c.img.dao.ImageDao;
import com.material.c2c.img.entity.TPXX;
import com.material.c2c.shoping.dao.ShoppingCartDao;
import com.material.c2c.shoping.entity.GWC;
import com.material.c2c.shoping.model.ShoppingCartDTO;
import com.material.c2c.util.BeanUtils;

/**
 * 购物车
 * @since 1.0
 * @version 1.0
 * @author QinYoubin (qin.youbin@sccaptain.com.cn)
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService{
  @Resource
  private ShoppingCartDao shoppingCartDao;
  @Resource
  private CommInfoDao commInfoDao;
  @Resource
  private ImageDao imageDao;
  @Override
  @Transactional
  public OperationResult add(GWC gwc) {
    gwc.setId(UUIDGenerator.generateUUIDStr());
    gwc.setTjsj(new Date());
    gwc.setZt(ShoppingCartStatus.NEW_ADD);
    gwc = shoppingCartDao.add(gwc);
    if(gwc==null) {
      return OperationResult.failed("添加失败！");
    }
    return OperationResult.SUCCEED;
  }
  
  @Override
  @Transactional
  public OperationResult remove(String id) {
    GWC gwc = shoppingCartDao.getOne(id);
    gwc.setZt(ShoppingCartStatus.REMOVE);
    gwc.setYcsj(new Date());
    shoppingCartDao.update(gwc);
    return OperationResult.SUCCEED;
  }
  
  @Override
  public List<ShoppingCartDTO> list(String userId) {
    // 查询购物车信息
    List<GWC> gwcList = shoppingCartDao.findByYhidAndZt(userId,ShoppingCartStatus.NEW_ADD);
    List<ShoppingCartDTO> dtoList = new ArrayList<ShoppingCartDTO>();
    for(GWC gwc:gwcList) {
      ShoppingCartDTO dto = new ShoppingCartDTO();
      BeanUtils.copyBeanNotNull2Bean(gwc, dto);
      //查询商品信息
      SPXX spxx= commInfoDao.getOne(gwc.getSpid());
      dto.setSpxx(spxx);
      List<TPXX> tpList =imageDao.listBySpid(spxx.getId());
      if(tpList != null) {
    	  dto.setTpxx(tpList.get(0));  
      }
      dtoList.add(dto);
    }
    return dtoList;
  }
  @Override
  public int getUserCartNum(String userId) {
	  int num = shoppingCartDao.countByYhidAndZt(userId,ShoppingCartStatus.NEW_ADD);
	  return num;
  }
}
